﻿using System;
using System.Collections.Generic;
using System.IO;

namespace _20160108_TestStudentExample
{
    class Student
    {
        static int idCounter;
        int id;
        string firstName;
        string lastName;

        public Student (string firstName, string lastName)
        {
            id = ++idCounter;
            this.firstName = firstName;
            this.lastName = lastName;
        }

        private Student(int id, string firstName, string lastName)
        {
            this.id = id;
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public void SaveStudentToFile(string path)
        {
            File.AppendAllText(path, String.Format("{0}\t{1}\t{2}\n", id, firstName, lastName));
        }

        public static void SaveStudentsListToFile(string path, List<Student> students)
        {
            foreach (var student in students)
                student.SaveStudentToFile(path);
        }

        public static List<Student> GetStudentsFromFile(string path)
        {
            if (!File.Exists(path))
                return null;
            string[] allStudents = File.ReadAllText(path).Split('\n');
            List<Student> students = new List<Student>();
            foreach (var student in allStudents)
            {
                if (!string.IsNullOrEmpty(student))
                {
                    string[] studentDetails = student.Split('\t');
                    students.Add(new Student(Int32.Parse(studentDetails[0]), studentDetails[1], studentDetails[2]));
                }
            }
            return students;
        }

        public override string ToString()
        {
            return String.Format("Студент {0}: {1} {2}", id, lastName, firstName);
        }
    }
}
